package com.hcw.bankdemob.exception;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName GlobalExceptionHandler
 * @description: 全局service异常处理包括异常出现次数
 * @author: hcw
 * @time: 2020/8/29 13:02
 */
@Aspect
@Component
@Slf4j
public class GlobalExceptionHandler {
    //用一个hashmap 来记录一下异常出现次数，以便后面优化业务。
    ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap();


    //service层的异常处理
    @Pointcut("execution(* com.hcw.bankdemo.service.*.*(..))")
    public void pointCut() {
    }
    //当抛出异常后执行的方法

    @AfterThrowing(throwing = "ex",pointcut = "pointCut()")
    public void afterThrowing(JoinPoint joinPoint, ServiceException  ex){
        //记录异常
        ExceptionEnum exceptionEnum = ex.getExceptionEnum();
        if(exceptionEnum !=  null){
            if(concurrentHashMap.contains(exceptionEnum.getEmsg())){
                //map包含就执行 记录+1
                ExceRecord exceRecord = (ExceRecord) concurrentHashMap.get(exceptionEnum.getEmsg());
                if (exceRecord == null) {
                    exceRecord.getNum().addAndGet(1);
                }else{
                    log.info("记录数据异常");
                }
            }else{
                //否则就存到map
                concurrentHashMap.put(exceptionEnum.getEmsg(), new ExceRecord(exceptionEnum.getEmsg(), new AtomicInteger(1)));
            }
        }else{
            log.info("数据异常");
        }
    }



}

/**
 * 记录异常次数
 */
class ExceRecord {
    //异常信息
    @Setter
    @Getter
    String emsg;
    //异常次数
    @Setter
    @Getter
    AtomicInteger num;

    public ExceRecord(String emsg, AtomicInteger num) {
        this.emsg = emsg;
        this.num = num;
    }
}